import axios from 'axios'
import {
	getCache
} from "@/utils/cache";
import {
	ElMessage
} from 'element-plus';

axios.defaults.withCredentials = true; //设置为true，解决跨域session丢失问题
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
//axios.defaults.baseURL = process.env.NODE_ENV === 'production' ? '/api/hgzx' : '/api';
const baseURL = process.env.NODE_ENV === 'production' ? '/route' : '/route';

const http = axios.create({
	baseURL: baseURL,
	timeout: 10000,
	headers: {
		// 'Content-Type': 'application/x-www-form-urlencoded'
	}
})

//在实例创建后改变默认值
// http.defaults.headers.common ['Authorization'] = AUTH_TOKEN;
// http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

// var cancelToken = axios.CancelToken;
// var source = cancelToken.source();

//添加请求拦截器
http.interceptors.request.use(
	function(config) {
		//在发送请求之前做某事
		console.log('http config:', config);
		const method = config.method;
		console.log('http method:', method);
		const accessToken = getCache('access_token');
		if (accessToken != null) {
			config.headers['access_token'] = accessToken;
		}

		// else {
		// 	window.location.href = "http://127.0.0.1:8081/#/login";
		// }
		return config;
	},
	function(error) {
		//请求错误时做些事
		ElMessage.error(error.response.data);
		return Promise.reject(error);
	});

//添加响应拦截器
http.interceptors.response.use(
	function(response) {
		//对响应数据做些事
		const httpRespStatus = response.status;
		console.log('http response.status:', httpRespStatus);
		console.log('http response:', response);
		return response.data;
	},
	function(error) {
		// console.log('http response error:', error);
		//请求错误时做些事
		ElMessage.error(error.response.data.message);

		const code = error.response.data.code;
		const message = error.response.data.message;
		switch (code) {
			case 4011:
				break;
			case 4031:
				break;
			default:
				ElMessage({
					message: message,
					type: 'warning'
				});
				break;
		}

		return Promise.reject(error);
	});

export default http;
